package com.datasecops.scannerservices.util;

import org.apache.commons.lang3.StringUtils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具类
 * @author: SunLingzhi
 * @time: 2022/8/9 14:59
 */
public class MD5Helper {

    public static String encode(String plainText) {
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] buffer = digest.digest(plainText.getBytes());
            // byte -128 ---- 127
            StringBuffer sb = new StringBuffer();
            for (byte b : buffer) {
                int a = b & 0xff;
                String hex = Integer.toHexString(a);

                if (hex.length() == 1) {
                    hex = 0 + hex;
                }
                sb.append(hex);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取雪花ID
    public static String getGuId(String plainText) {
        String guId = encode(plainText);
        if (StringUtils.isNotBlank(guId)){
            StringBuilder builder = new StringBuilder(guId);
            builder.insert(8,"-");
            builder.insert(13,"-");
            builder.insert(18,"-");
            builder.insert(23,"-");
            guId = builder.toString().toUpperCase();
        }
        return guId;
    }


    public static void main(String[] args) {
        System.out.println(MD5Helper.getGuId("10.26.18.59:3313"));
    }
}
